package com.kning.poiword.test;

import com.kning.poiword.model.Text;
import com.kning.poiword.replace.ReplaceDocument;
import com.kning.poiword.replace.ReplaceDocumentImpl;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * @version : 1.0
 * @ClassName: ReplaceText
 * @Description: TODO
 * @author : 王康宁
 * @date : 2020/1/7
 **/
public class ReplaceText {

    public static void main(String[] args) throws Exception{
        testReplaceText();
    }
    public static void testReplaceText() throws Exception {
        ReplaceDocument replaceDocument = new ReplaceDocumentImpl();

        final String returnurl = "D:\\PoiWordDemo\\result.docx";

        final String templateurl = "D:\\PoiWordDemo\\test.docx";

        InputStream is = new FileInputStream(new File(templateurl));
        XWPFDocument doc = new XWPFDocument(is);
        Text text = new Text();
        text.setMark("mark1");
        text.setContent("mark1:content1--test replace text");
        List<Text> texts = Arrays.asList(text);

        replaceDocument.replaceAllComponent(doc, texts, null, null, null);
        // 保存结果文件
        try {
            File file = new File(returnurl);
            if (file.exists()) {
                file.delete();
            }
            FileOutputStream fos = new FileOutputStream(returnurl);
            doc.write(fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
